/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.postorder.flow.craete;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.lxk.oms.order.domain.vo.OmsOrderItemVo;
import com.lxk.oms.order.domain.vo.OmsOrderVo;
import com.lxk.oms.order.service.IOmsOrderItemService;
import com.lxk.oms.order.service.IOmsOrderService;
import com.lxk.oms.postorder.domain.enums.PostOrderEnums;
import com.lxk.oms.postorder.domain.req.CreatePostOrderReq;
import com.lxk.oms.postorder.service.IOmsPostOrderService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.ValidationUtils;

import java.util.ArrayList;
import java.util.List;

import static com.lxk.oms.postorder.flow.craete.FlowPostOrderNodeConst.COMMENT_FILL_POST_ORDER_NODE;

/**
 * 参数填充
 *
 * @author heyi
 * 2024/9/28
 */
@Slf4j
@AllArgsConstructor
@LiteflowComponent(COMMENT_FILL_POST_ORDER_NODE)
public class PostOrderFillContextNode extends NodeComponent {
    private final IOmsOrderService omsOrderService;
    private final IOmsOrderItemService omsOrderItemService;
    private final IOmsPostOrderService postOrderService;

    @Override
    public void beforeProcess() {
        CreatePostOrderReq req = this.getRequestData();
        ValidationUtils.validate(req);
        if (CollUtil.isEmpty(req.getPostOrderItemList())) {
            req.setPostOrderItemList(new ArrayList<>());
        }
        Boolean exist = postOrderService.existByOrderNo(req.getOrderNo(), PostOrderEnums.PostOrderStatus.REVIEW, PostOrderEnums.PostOrderStatus.RETURNED, PostOrderEnums.PostOrderStatus.ING, PostOrderEnums.PostOrderStatus.PENDING_REFUND);
        if (exist) {
            log.error("您已提交售后:{}", req.getOrderNo());
            throw new ServiceException("您已提交售后,请勿重复提交");
        }
    }

    @Override
    public void process() throws Exception {
        CreatePostOrderReq req = this.getRequestData();
        PostOrderCreateContext context = this.getContextBean(PostOrderCreateContext.class);
        MapstructUtils.convert(req, context);
        OmsOrderVo omsOrderVo = omsOrderService.queryByOrderSn(req.getOrderNo(), req.getUserId());
        if (ObjectUtil.isNotNull(omsOrderVo)) {
            List<OmsOrderItemVo> omsOrderItemVos = omsOrderItemService.queryByOrderIdList(omsOrderVo.getId());
            context.setOmsOrderItemVos(omsOrderItemVos);
        }
        context.setOmsOrder(omsOrderVo);
        ValidationUtils.validate(context);
    }
}
